package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User:xieChao
 * Date:2022/12/5 16:10
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
     private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setCharacterEncoding("utf8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        System.out.println("username=" + username + ", password=" + password);
        if(username == null || "".equals(username) || password == null || "".equals(password)){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write(" error !!!");
            return;
        }

        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if(user == null || !user.getPassword().equals(password)){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write(" error !!!");
            return;
        }
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
        //跳转
        resp.sendRedirect("blog_list.html");
    }


    /**
     * 用户发过来登录请求，判断是否登录成功
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        HttpSession session = req.getSession(false);
        if(session == null){
            //检查会话是否存在，不存在说明未登录
            User user = new User();
            resp.getWriter().write(objectMapper.writeValueAsString(user));
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            //有会话，会话里没有user对象，也视为未登录
            user = new User();
            resp.getWriter().write(objectMapper.writeValueAsString(user));
            return;
        }
        //已经登录,同时具备session和user
        //此处，密码不能返回给前端
        user.setPassword("");
        resp.getWriter().write(objectMapper.writeValueAsString(user));
    }
}
